package com.sxm.yiwei.fragments;


import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;

import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.sxm.yiwei.R;
import com.sxm.yiwei.activitis.AddLinkmanActivity;
import com.sxm.yiwei.activitis.HelpActivity;
import com.sxm.yiwei.activitis.SlideListView;
import com.sxm.yiwei.adapters.ListViewSlideAdapter;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class LinkAddressFragment extends Fragment implements View.OnClickListener{


    private PullToRefreshListView listview;
    private SlideListView sendlist;
    private Button addressadd;
    private ImageView linksendback;
    private SharedPreferences sharedPreferences;
    private String appId;
    private String userId;
    private String token;
    private String is="0";
    private String url = "http://192.168.3.77:8088/YiViOnlineServer";
    private JSONArray array;
    private HashMap map;
    private ArrayList<HashMap<String,String>> linkList;
    private String id;
    private String from;
    private Intent in;
    private static final int ADDRESSTWO = 1002;
    private static final int ADDRESSONE = 1001;
    private static final int ADDRESSTHREE = 1003;
    private ImageView nodata;
    private ListViewSlideAdapter adapter;
    @Override
    public void onStart() {
        super.onStart();
        /*linkList.clear();
        getLinkdata();*/


    }

    public LinkAddressFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_link_address, container, false);
        sendlist = (SlideListView)view.findViewById(R.id.sendlistview);
        sharedPreferences = getActivity().getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        appId = sharedPreferences.getString("appid", "0");
        userId = sharedPreferences.getString("userId", "1");
        token = sharedPreferences.getString("token", "2");
        nodata = (ImageView) view.findViewById(R.id.addressnodata);
        Intent intent = getActivity().getIntent();
        from = intent.getStringExtra("from");
        linkList = new ArrayList<>();
        linkList.clear();
        getLinkdata();

        return view;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden){
            return;
        }else {
            linkList.clear();
            getLinkdata();
        }
    }

    private List getLinkdata() {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/contact/getContactList");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject j = new JSONObject();
        j.put("type","0");
        params.addParameter("params",j.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {



            @Override
            public void onSuccess(String result) {

                com.alibaba.fastjson.JSONObject obj = JSON.parseObject(result);
                String data = obj.getString("data");
                array = JSONArray.parseArray(data);
                if (array.size()==0){

                }else {
                    nodata.setVisibility(View.GONE);
                    for (int i = 0; i < array.size(); i++) {
                        map = new HashMap();
                        com.alibaba.fastjson.JSONObject obj1 = JSON.parseObject(String.valueOf(array.get(i)));
                        String name = obj1.getString("name");
                        final String phone = obj1.getString("phone");
                        String address = obj1.getString("address");
                        String longitude = obj1.getString("longitude");
                        String latitude = obj1.getString("latitude");
                        id = obj1.getString("id");
                        map.put("name",name);
                        map.put("phone",phone);
                        map.put("address",address);
                        map.put("id", id);
                        map.put("longitude", longitude);
                        map.put("latitude", latitude);
                        linkList.add(map);


                    }
                }

                adapter = new ListViewSlideAdapter(getActivity(),linkList);
                sendlist.setAdapter(adapter);
                adapter.setOnClickListenerEditOrDelete(new ListViewSlideAdapter.OnClickListenerEditOrDelete() {
                    @Override
                    public void OnClickListenerEdit(int position) {
                        // 编辑
                        Intent intent = new Intent(getActivity(),AddLinkmanActivity.class);
                        HashMap<String, String> bianji = linkList.get(position);
                        intent.putExtra("name1",bianji.get("name"));
                        intent.putExtra("phone1",bianji.get("phone"));
                        intent.putExtra("address1",bianji.get("address"));
                        intent.putExtra("is",is);
                        startActivity(intent);
                    }
                    @Override
                    public void OnClickListenerDelete(final int position) {
                        // 删除
                        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),R.style.NoBackGroundDialog);
                        View view = LayoutInflater.from(getActivity()).inflate(R.layout.cancel_servicedialog, null);

                        builder.setView(view);
                        Button cancelbt = (Button) view.findViewById(R.id.cancel_cancelbt);
                        Button surebt = (Button) view.findViewById(R.id.cancel_surebt);
                        TextView t2 = (TextView) view.findViewById(R.id.cancel_t2);
                        t2.setText("是否删除此联系人 ?");
                        final AlertDialog dialog = builder.create();
                        cancelbt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                            }
                        });
                        surebt.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                HashMap<String, String> hashMap = linkList.get(position);
                                String id = hashMap.get("id");
                                removeLink(id,position);
                                adapter.notifyDataSetChanged();

                                dialog.dismiss();
                            }
                        });
                        dialog.show();



                    }
                            });
                            adapter.notifyDataSetChanged();
                            if (from.equals("2")){
                            sendlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        HashMap<String, String> hashMap = linkList.get(position);
        String name1 = hashMap.get("name");
        String address1 = hashMap.get("address");
        String phone1 = hashMap.get("phone");
        String id1 = hashMap.get("id");

        Intent intent = new Intent(getActivity(), HelpActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("name",name1);
        bundle.putString("address",address1);
        bundle.putString("phone",phone1);
        bundle.putString("id",id1);
        intent.putExtras(bundle);
        getActivity().setResult(Activity.RESULT_OK,intent);
        getActivity().finish();
        }
        });
        }else {

        }


        }
@Override
public void onError(Throwable ex, boolean isOnCallback) {
        }
@Override
public void onCancelled(CancelledException cex) {
        }
@Override
public void onFinished() {
        }
        });
        return linkList;
        }

private void removeLink(String id, final int position) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+"/contact/removeContact");
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);
        JSONObject j = new JSONObject();
        j.put("contactId",id);
        params.setBodyContent(j.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
@Override
public void onSuccess(String result) {

        linkList.remove(position);
    try {
        sendlist.turnToNormal();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendlist.invalidate();

        }

@Override
public void onError(Throwable ex, boolean isOnCallback) {

        }

@Override
public void onCancelled(CancelledException cex) {

        }

@Override
public void onFinished() {

        }
        });


        }

@Override
public void onClick(View v) {
        switch (v.getId()){
        case R.id.link_send_back:
        break;
        case R.id.address_addbt:
        Intent intent = new Intent(getActivity(),AddLinkmanActivity.class);
        intent.putExtra("is",is);
        startActivity(intent);
        break;
        }
        }

        }
